package cn.runagain.demo.wechatminiappdemo.utils;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;

    /**
     * created by
     *
     * @author tuxianchao
     * @date 2018/6/15 上午10:49
     */
    public class ShellUtil {

        /**
         * @param shellString shell command
         * @return 每一行结果
         */
        public static List<String> callShell(String shellString) {
            List<String> result = new ArrayList<String>();
            BufferedReader bufferedReader = null;
            try {
                Process process = Runtime.getRuntime().exec(shellString);
                int exitValue = process.waitFor();
                if (0 != exitValue) {
                    System.out.println("call shell failed. error code is :" + exitValue);
                }
                //正常结束,Process的waitFor()方法返回0
                bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    result.add(line);
                }
            } catch (Throwable e) {
                System.out.println("call shell failed. " + e);
            } finally {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }

        public static void main(String[] args) {
            for (String line : callShell("jps -v")) {
                System.out.println(line);
            }
        }

    }
